<template>
  <div class="p-6 space-y-4">
    <el-card shadow="never" class="rounded-lg">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="onSearch">
        <el-row :gutter="12" align="bottom">
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备位号或名称">
              <el-input v-model="filters.keyword" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="检维修项目">
              <el-select v-model="filters.project" placeholder="请选择" clearable>
                <el-option v-for="p in projectOptions" :key="p" :label="p" :value="p" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="计划检维修日期">
              <el-date-picker v-model="filters.planDate" type="date" placeholder="选择日期" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="4" class="flex justify-end items-end">
            <el-button type="primary" :loading="queryLoading" @click="onSearch">
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="设备位号" prop="code" min-width="120" />
          <el-table-column label="设备名称" prop="name" min-width="140" />
          <el-table-column label="计划检维修日期" prop="planDate" min-width="140" />
          <el-table-column label="实际检维修日期" prop="actualDate" min-width="140" />
          <el-table-column label="检修类型" prop="type" min-width="120" />
          <el-table-column label="检修项目" prop="project" min-width="160" />
          <el-table-column label="所属部门" prop="department" min-width="120" />
          <el-table-column label="状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.status)">{{ scope.row.statusLabel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="负责人" prop="principal" min-width="120" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-link type="danger" @click="onDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

interface OverhaulRecord {
  id: number;
  code: string;
  name: string;
  planDate: string;
  actualDate: string;
  type: string;
  project: string;
  department: string;
  status: string;
  statusLabel: string;
  principal: string;
}

const projectOptions = ['更换密封', '轴承更换', '机封检修', '电机检修', '管线更换'];

const filters = reactive({
  keyword: '',
  project: '',
  planDate: '' as any
});

const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const statusTagMap: Record<string, string> = {
  done: 'primary',
  delay: 'warning',
  pending: 'info'
};
const statusTagType = (s: string) => statusTagMap[s] ?? 'info';

const allRecords = ref<OverhaulRecord[]>([]);

const mockInit = () => {
  const codes = ['VO101B', 'VO102A', 'PX305', 'HT450', 'SA600', 'IB220', 'EL330'];
  const names = ['主反应釜', '备用反应釜', '冷却循环泵', '换热器', '安全阀', '仪表盘', '电机'];
  const types = ['计划检修', '故障检修'];
  const principals = ['王伟', '李娜', '张敏', '刘洋', '陈杰', '杨静', '黄磊', '周玲', '吴涛', '赵敏'];
  const departments = ['生产部门', '设备部', '安环部', '工艺部'];
  const statuses: Array<[string, string]> = [
    ['done', '完成'],
    ['delay', '延期'],
    ['pending', '未完成']
  ];
  const list: OverhaulRecord[] = [];
  let id = 1;
  const n = 10; // 固定条数，刷新不变
  for (let i = 0; i < n; i++) {
    const code = codes[i % codes.length];
    const name = names[i % names.length];
    const type = types[i % types.length];
    const project = projectOptions[i % projectOptions.length];
    const department = departments[i % departments.length];
    const [status, statusLabel] = statuses[i % statuses.length];
    const principal = principals[i % principals.length];
    const month = (i % 9) + 1;
    const planDate = `2024-${String(month).padStart(2, '0')}-12`;
    const actualDate = `2024-${String(month).padStart(2, '0')}-${10 + (i % 10)}`;
    list.push({ id: id++, code, name, planDate, actualDate, type, project, department, status, statusLabel, principal });
  }
  allRecords.value = list;
};

const tableData = ref<OverhaulRecord[]>([]);

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const formatDate = (d: any) => {
  if (!d) return '';
  const dt = new Date(d);
  const y = dt.getFullYear();
  const m = String(dt.getMonth() + 1).padStart(2, '0');
  const da = String(dt.getDate()).padStart(2, '0');
  return `${y}-${m}-${da}`;
};

const applyFilter = () => {
  const k = filters.keyword.trim();
  const pDate = filters.planDate ? formatDate(filters.planDate) : '';
  return allRecords.value.filter((r) => {
    const matchK = k ? r.code.includes(k) || r.name.includes(k) : true;
    const matchProj = filters.project ? r.project === filters.project : true;
    const matchPlan = pDate ? r.planDate === pDate : true;
    return matchK && matchProj && matchPlan;
  });
};

const refreshTable = (list: OverhaulRecord[]) => {
  pagination.total = list.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  tableData.value = list.slice(start, start + pagination.pageSize);
};

const fetchList = async (btn = true) => {
  if (btn) queryLoading.value = true;
  tableLoading.value = true;
  try {
    await new Promise((r) => setTimeout(r, 200));
    const filtered = applyFilter();
    refreshTable(filtered);
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchList();
};
const onSizeChange = (s: number) => {
  pagination.pageSize = s;
  pagination.currentPage = 1;
  fetchList(false);
};
const onPageChange = (p: number) => {
  pagination.currentPage = p;
  fetchList(false);
};

const onDelete = async (row: OverhaulRecord) => {
  try {
    await ElMessageBox.confirm(`确认删除设备“${row.code}”的检维修记录？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    tableLoading.value = true;
    await new Promise((r) => setTimeout(r, 200));
    allRecords.value = allRecords.value.filter((x) => x.id !== row.id);
    if ((pagination.currentPage - 1) * pagination.pageSize >= allRecords.value.length && pagination.currentPage > 1) pagination.currentPage -= 1;
    await fetchList(false);
    ElMessage.success('删除成功');
  } catch (e: any) {
    if (e !== 'cancel' && e !== 'close') ElMessage.error('删除失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

onMounted(async () => {
  mockInit();
  await fetchList(false);
});
</script>
